package com.kaifamiao.wendao.dao;

import com.kaifamiao.wendao.entity.Customer;
import com.kaifamiao.wendao.entity.Topic;
import org.apache.commons.dbutils.ResultSetHandler;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class TopicDao extends BaseDao<Topic, Long> {

    private CustomerDao customerDao = new CustomerDao();

    private static final String SELECT_ALL = "SELECT * FROM t_topics ORDER BY id desc";
    private static final String SELECT_ALL_BY_CID = "SELECT * FROM t_topics WHERE customer_id=?";
    private static final String INSERT_ONE = "INSERT INTO t_topics (id,title,content,customer_id,publish_time,publish_address,priority,tags) VALUES(?,?,?,?,?,?,?,?)";
    private static final String SELECT_ALL_BY_TAG = "SELECT * FROM t_topics WHERE tags=?";
    private static final String UPDATE_ONE = "UPDATE t_topics SET title=?,content=?,publish_time=?,publish_address=?,priority=? ,customer_id=?,tags=? WHERE id=?";
    private static final String DELETE_ONE = "DELETE FROM t_topics WHERE id=?";
    private static final String SELECT_ONE_BY_ID = "SELECT * FROM t_topics WHERE id=?";
    private static final String SELECT_ALL_BY_WORD = "SELECT * FROM t_topics WHERE title LIKE ? ";

    private Topic wrap(ResultSet rs) throws SQLException {
        Topic topic = new Topic();
        topic.setId(rs.getLong("id"));
        topic.setTitle(rs.getString("title"));
        topic.setContent(rs.getString("content"));
        Long cid = rs.getLong("customer_id");
        topic.setAuthor(customerDao.find(cid));
        Timestamp timestamp = rs.getTimestamp("publish_time");
        LocalDateTime dateTime = timestamp == null ? null : timestamp.toLocalDateTime();
        topic.setPublishTime(dateTime);
        topic.setPublishAddress(rs.getString("publish_address"));
        topic.setPriority(rs.getInt("priority"));
        return topic;
    }

    @Override
    public boolean save(Topic topic) {
        LocalDateTime dateTime = topic.getPublishTime();
        Timestamp timestamp = dateTime == null ? null : Timestamp.valueOf(dateTime);
        Object[] params = {topic.getId(), topic.getTitle(), topic.getContent(), topic.getAuthor().getId(), timestamp, topic.getPublishAddress(), topic.getPriority(), topic.getTag()};
        try {
            return runner.update(INSERT_ONE, params) == 1;
        } catch (SQLException e) {
            throw new RuntimeException("保存话题失败", e);
        }
    }

    @Override
    public boolean update(Topic topic) {

        Object[] params = {topic.getTitle(), topic.getContent(), topic.getPublishTime(), topic.getPublishAddress(), topic.getPriority(), topic.getAuthor().getId(), topic.getTag(), topic.getId()};
        try {
            return runner.update(UPDATE_ONE, params) == 1;
        } catch (SQLException e) {
            throw new RuntimeException("更改话题失败", e);
        }
    }

    @Override
    public boolean remove(Long id) {
        try {
            return runner.update(DELETE_ONE, id) == 1;
        } catch (SQLException e) {
            throw new RuntimeException("删除话题失败", e);
        }
    }

    @Override
    public List<Topic> findAll() {
        ResultSetHandler<List<Topic>> rsHandler = rs -> {
            List<Topic> list = new ArrayList<>();
            while (rs.next()) {
                Topic t = wrap(rs);
                list.add(t);
            }
            return list;
        };
        try {
            return runner.query(SELECT_ALL, rsHandler);
        } catch (SQLException e) {
            throw new RuntimeException("查询所有话题失败", e);
        }
    }

    public List<Topic> findAll_Order(String tag) {
        ResultSetHandler<List<Topic>> rsHandler = rs -> {
            List<Topic> list = new ArrayList<>();
            while (rs.next()) {
                Topic t = wrap(rs);
                list.add(t);
            }
            return list;
        };
        try {
            return runner.query(SELECT_ALL_BY_TAG, rsHandler, tag);
        } catch (SQLException e) {
            throw new RuntimeException("查询所有话题失败", e);
        }
    }

    public List<Topic> findAll(Long CustomerId) {
        ResultSetHandler<List<Topic>> rsHandler = rs -> {
            List<Topic> list = new ArrayList<>();
            while (rs.next()) {
                Topic t = wrap(rs);
                list.add(t);
            }
            return list;
        };
        try {
            return runner.query(SELECT_ALL_BY_CID, rsHandler, CustomerId);
        } catch (SQLException e) {
            throw new RuntimeException("查询所有话题失败", e);
        }
    }

    public List<Topic> findAll(String word) {
        ResultSetHandler<List<Topic>> rsHandler = rs -> {
            List<Topic> list = new ArrayList<>();
            while (rs.next()) {
                Topic t = wrap(rs);
                list.add(t);
            }
            return list;
        };
        try {
            return runner.query(SELECT_ALL_BY_WORD, rsHandler, '%' + word + '%');
        } catch (SQLException e) {
            throw new RuntimeException("查询所有话题失败", e);
        }
    }


    @Override
    public Topic find(Long id) {
        ResultSetHandler<Topic> resultSetHandler = rs -> {
            if (rs.next()) {
                Topic topic = wrap(rs);
                return topic;
            }
            return null;
        };
        try {
            return runner.query(SELECT_ONE_BY_ID, resultSetHandler, id);
        } catch (SQLException e) {
            throw new RuntimeException("查询失败", e);
        }
    }

}
